<?php

class TopUpController extends BaseController {

	// Table
	public $table = 'topup';

	// Eloquent Model
	public $model = 'Topup';

	// Base - Route Name
	public $base = 'top-up';

	// Localization
	public $local = 'en';

	// Language File Name
	public $language = 'topup';

	// Breadcrumbs 
	public $breadcrumbs = [ ['link' => 'top-up' , 'title' => 'Top-Up'] ];
	
	// Set List Data - Input, Object
	public function setListData( $data, $object ) {
		// Call the syncOrders and 
		$this->_syncOrders( $object );
		// Cancel Order who did not response
		$this->_cancelPendingTopup( $object );
		// Cancel with No Topup Info
		$this->_cancelWithNoTopupInfo( $object );
		// Cancel Order with Cancel Topup
		$this->_cancelOrderWithCancelTopup( $object );
		//Topup list and filtering
		$object = $this->_getTopUpList( $data, $object );
		
		
		return $object;
	}
	
	// Add List Data - Additional Data on List
	public function addListData( $data ) {
		$data['companies'] = array('All Clients');
		
		$get_company_id=array();
		$get_company_id = Order::distinct()->where('status','=',Constant::ORDER_TOPUP)->lists('COMPANY_id');
		$get_company_name = Company::whereIn('id', $get_company_id )->get(array('id','name'));

		foreach( $get_company_name as $company ){
			$get_branch = CompanyBranch::where( 'COMPANY_id','=', $company->id)->get(array('id', 'name'));
			foreach( $get_branch as $branch )
				$data['companies'][$branch->id] = ucwords($company->name).' - '.$branch->name;
		}
		
		return $data;
	}
	
	/**
	 * @author Raymond
	 * Display topup with filtering
	 * @param  $data, $object
	 * @return $object
	 */
	
	private function _getTopUpList( $data, $object ) {
		$object = $object->select( array('topup.LOGIN_id', 'topup.ORDER_id', 'topup.id', 'topup.status as topup_status','topup.ORDER_id',
				'login.lastname','login.firstname',
				'company_branch.name',
				'order.status as order_status', 'order.points', 'order.created_at', 'order.payment_method')
		);
		
		$object = $object->join( 'login', 'topup.LOGIN_id', '=', 'login.id' );
		$object = $object->join( 'order', 'topup.ORDER_id', '=', 'order.id' );
		$object = $object->join( 'company', 'order.COMPANY_id','=','company.id' );
		$object = $object->join( 'company_branch', 'login.BRANCH_id', '=', 'company_branch.id');
		$object = $object->where( 'order.payment_method', '<>', 'points');
		$object = $object->where( 'order.created_at', '<', DB::raw( '(NOW() - INTERVAL 24 HOUR)' ) );
		

		if( !empty( $data['filter_payment_method'] ) )
			$object = $object->where( 'order.payment_method', '=', $data['filter_payment_method'] );
		
		if( !empty( $data['filter_order_status'] ) ){
			$order_status = ( $data['filter_order_status'] == 8 ) ? Constant::ORDER_TOPUP :  $data['filter_order_status'];
			$object = $object->where( 'order.status', $order_status );
		}

		if( !empty( $data['filter_order_id'] ) ){
			$order_ids = preg_split('/\r\n|[\r\n]/', $data['filter_order_id']);
			$filtered_sales_order_ids = array_filter(array_unique($order_ids));

			if ( !empty($filtered_sales_order_ids) )
				$object = $object->whereIn( 'topup.ORDER_id', $filtered_sales_order_ids );
		}
		
		if( !empty( $data['filter_topup_status'] ) ) {
			
			if( $data['filter_topup_status'] == 3 )
				$object = $object->where( 'topup.status', '=', Constant::TOPUP_NORMAL );
			else
				$object = $object->where( 'topup.status', '=', $data['filter_topup_status'] );
		}
		
		if( !empty( $data['filter_date_ref_from'] ) ) {
			$date_from = date( "Y-m-d", strtotime( $data['filter_date_ref_from'] ) );
			
			$object = $object->whereHas('topupInformation', function ( $q ) use ( $date_from ) {
				$q->where( 'date', '>=', $date_from.' 00:00:00' );
			});
		}
		
		if( !empty( $data['filter_date_ref_to'] ) ){
			$date_to = date( "Y-m-d", strtotime( $data['filter_date_ref_to'] ) );
			
			$object = $object->whereHas('topupInformation', function ( $q ) use ( $date_to ) {
				$q->where( 'topup_information.date', '<=', $date_to.' 23:59:59' );
			});
		}
		
		if( !empty( $data['filter_date_ref_from'] ) &&
			!empty( $data['filter_date_ref_to'] ) ) {
				$date_from = date( "Y-m-d", strtotime( $data['filter_date_ref_from'] ) );
				$date_to = date( "Y-m-d", strtotime( $data['filter_date_ref_to'] ) );
				
				$object = $object->whereHas('topupInformation', function ( $q ) use ( $date_from,$date_to ) {
					$q->whereBetween( 'topup_information.date', array( $date_from . ' 00:00:00', $date_to . ' 23:59:59' ) );
				});
		}
		
		if( !empty( $data['filter_client'] ) )
			$object = $object->where('company_branch.id', '=', $data['filter_client'] );
		
		if(!empty($data['filter_employee_id']))
			$object = $object->where('login.id', '=', $data['filter_employee_id']);
		
		if(!empty($data['filter_employee_firstname']))
			$object = $object->where('login.firstname', 'LIKE','%' . $data['filter_employee_firstname']. '%' );
		
		if(!empty($data['filter_employee_lastname']))
			$object = $object->where('login.lastname', 'LIKE', '%' .$data['filter_employee_lastname']. '%');

		return $object;
	}

	// Process before updating data
	public function preUpdate( $data ) {
		foreach( $data['topup_information'] as $index=>$topup_info ) {
		
			$topup_info['amount'] = trim( $topup_info['amount'] );
			$topup_info['reference_number'] = trim( $topup_info['reference_number'] );
			$topup_info['date'] = trim( $topup_info['date'] );
			
			/*if( empty( ( float )$topup_info['amount'] ) ) 
				$this->error['topup_information'][$index]['amount'][] = 'Please enter amount';*/
			if( !is_numeric( $topup_info['amount'] ) )
				$this->error['topup_information'][$index]['amount'][] = 'Please input numbers and period only';
			
			if( $topup_info['reference_number'] == '' )
				$this->error['topup_information'][$index]['reference_number'][] = 'This field is required';
			
			$date = DateTime::createFromFormat( 'Y-m-d H:i:s', $topup_info['date'] );
			if ( !$date ) 
				$this->error['topup_information'][$index]['date'][] = 'Your date format is invalid';
		}
		// Validate comment when the action is cancel or pending
		if( $data['topup_action'] == Constant::TOPUP_PENDING_ACTION ||
				$data['topup_action'] == Constant::TOPUP_CANCEL_ACTION ){
				$this->rules['comment'] = 'required';
		}
		return $data;
	}
	
	public function postUpdate( $data, $object ) {
		// If the user choose update only it will update topup information		
		if( empty( $data['topup_action'] ) ){
			foreach( $data['topup_information'] as $value ){
				$object->topupInformation()->where('topup_information.id', '=', $value['id'] )
				->update( array( 'reference_number' => $value['reference_number'], 'amount' => $value['amount'], 'date' => $value['date'] ) );
			}	
		}
		else if( $data['topup_action'] == Constant::TOPUP_PENDING_ACTION ){
			
			$object->status = Constant::TOPUP_PENDING;
			$object->comment = $data['comment'];
			$object->save();
			// This is the content for email
			$content=$object::select( 'login.lastname','login.firstname','login.middlename','topup.ORDER_id','topup.comment',
					'topup_information.image','topup_information.reference_number','topup_information.amount',
					'topup_information.date')
			->join( 'topup_information','topup_information.TOPUP_id','=','topup.id' )
			->join( 'login','topup.LOGIN_id','=','login.id' )
			->where( 'topup.id', '=', $object->id )->first();
			
			/*Mail::send( 'emails.topup-status', array( 'content' => $content ), function( $message ) use( $content ){
				$message->to( 'glorianmond@gmail.com', $content->lastname )->subject( 'Your Order is move to pending' );
			});
			*/
		}
		// Cancel the Topup
		else if( $data['topup_action'] == Constant::TOPUP_CANCEL_ACTION ){
				$object->status= Constant::TOPUP_CANCEL;
				$object->comment = $data['comment'];
				$object->save();
				//Notify Employees by sending email
				/*Mail::send( 'emails.topup-status', array( 'content' => $reimbursement_d ), function( $message ) use( $reimbursement_d ){
				 $message->to( 'glorianmond@gmail.com', $reimbursement_d['employee']->firstname )->subject( 'Reimbursement Status Update' );
						});
				*/
			}
		// Move to processing.
		else if( $data['topup_action'] == Constant::TOPUP_PROCESSING_ACTION ){
			$object->status=Constant::TOPUP_NORMAL;
			$object->save();
			// Save the topup information
			foreach( $data['topup_information'] as $value ){
				$object->topupInformation()->where('topup_information.id', '=', $value['id'] )
				->update( array( 'reference_number' => $value['reference_number'], 'amount' => $value['amount'], 'date' => $value['date'] ) );
			}
			
			$update_order = Order::find( $object->ORDER_id );
			$update_order->status = $data['topup_action'];
			$update_order->save();
			
			$update_order_product = OrderProduct::where( 'ORDER_id','=',$object->ORDER_id )
			->update( array( 'status' =>$data['topup_action'] ) );
			// This is for the value in Webservice/API
			$update_order_client = Order::select( 'company.code', 'order.EMPLOYEE_id', 'order.id', 'order.status' )
			->join( 'company','order.COMPANY_id', '=', 'company.id' )
			->where( 'order.id', '=', $object->ORDER_id )
			->first();
			
			/*Webservice::getRequestApi( 'update_topup_client', array($update_order_client->code, $update_order_client->EMPLOYEE_id, 
			$update_order_client->id, $update_order_client->status ) );
			*/
		}
		$action= Lang::get('topup.topup_action');
		Session::flash('last_action',$action[$data['topup_action']]);
		return $data;
	}

	/**
	 * ...
	 * @author Raymond
	 * @param $object
	 * @return void
	 */
	private function _syncOrders( $object ) {
		
		$query = Order::where( 'payment_method', '<>', Constant::PAYMENT_POINTS );
		$query = $query->where( 'status', '=', Constant::ORDER_TOPUP );
		$query = $query->where( 'created_at', '<', DB::raw( '(NOW() - INTERVAL 24 HOUR)' ) );
		// has data in Topup table? don't include in new list
		if ( $topup_orders = $object->lists('ORDER_id') ) 
			$query = $query->whereNotIn( 'id', $topup_orders );

		$query = $query->where( 'archived', 0 );
		$query = $query->get( array( 'EMPLOYEE_id', 'id', 'payment_method' ) );
		// has no result? end
		if ( !$query->count() ) return;

		$new_topups = array();
		foreach( $query as $order ) {
			$new_topups[] = array(
				'LOGIN_id' => $order->EMPLOYEE_id,
				'ORDER_id' => $order->id
			);
		}
		
		$object->insert( $new_topups );
	}
	
	/**
	 * ...Cancel Order beyond 48 hours for those doesn't update topup referrence
	 * @author Raymond
	 * @param null
	 * @return void
	 */
	private function _cancelPendingTopup( $object ){
		
		$topup_details = $object->where( 'updated_at','<>','0000-00-00 00:00:00' )
		->where( 'status','=', Constant::TOPUP_PENDING )
		->where( 'updated_at','<' ,DB::raw( '(NOW() - INTERVAL 2 DAY)' ) );
		if( $topup_details->count() ){
			$topup_details=$topup_details->get();
			foreach( $topup_details as $value ){
				$cancel_pending = Order::find( $value->ORDER_id );
				$cancel_pending->status = Constant::ORDER_CANCELLED;
				$cancel_pending->save();
				
				$cancel_topup=Topup::find( $value->id );
				$cancel_topup->status=Constant::TOPUP_NORMAL;
				$cancel_topup->save();
			}
		}
	}
	
	/**
	 * ...Cancel Order beyond 48 hours for those doesn't upload topup reference.
	 * @author Raymond
	 * @param null
	 * @return void
	 */
	private function _cancelWithNoTopupInfo( $object ){
		
		$topup_details = $object->where( 'updated_at', '=', '0000-00-00 00:00:00' )
		->where( 'status', '=', Constant::TOPUP_NORMAL )
		->where( 'created_at', '<', DB::raw( '(NOW() - INTERVAL 2 DAY)' ) )
		->whereRaw( '(SELECT COUNT(*) FROM topup_information WHERE topup.id = TOPUP_id)=0' );

		$multiple_order_id=array();
		if( $topup_details->count() ){
			$topup_details=$topup_details->get();
			foreach( $topup_details as $value ){
				$cancel_topup = Order::find( $value->ORDER_id );
				$cancel_topup->status = Constant::ORDER_CANCELLED;
				$cancel_topup->save();
			
				$multiple_order_id=array( $value->ORDER_id );
			}
			$this->_cancelClientOrder( $multiple_order_id );
		}
	}
	
	/**
	 * ..Cancel the Order beyond 48 hours for the topup that was cancel
	 * @author Raymond
	 * @param $object
	 * return void
	 */
	private function _cancelOrderWithCancelTopup( $object ){
	
		$topup_details = $object->where( 'updated_at','<>','0000-00-00 00:00:00' )
		->where( 'status','=', Constant::TOPUP_CANCEL )
		->where( 'updated_at','<' ,DB::raw( '(NOW() - INTERVAL 2 DAY)' ) );
	
		if( $topup_details->count() ){
			$topup_details=$topup_details->get();
			foreach( $topup_details as $value ){
				$cancel_pending = Order::find( $value->ORDER_id );
				$cancel_pending->status = Constant::ORDER_CANCELLED;
				$cancel_pending->save();
	
				$cancel_topup=Topup::find( $value->id );
				$cancel_topup->status = Constant::TOPUP_NORMAL;
				$cancel_topup->save();
			}
		}
	}
	
	/**
	 * Exporting topup list
	 * @author Raymond
	 * @param null
	 * @return void
	 */
	public function exportOrder( ){
		// $get_data = $this->_getTopUpList( Input::all(), Topup::where( 'topup.archived', 0) ); # Commented Out Aimon 2015-03-09
		$get_data = $this->_getTopUpList( Input::all(), Topup::where( 'topup.archived','=', 0) );
		$get_topup['topup_list'] = $get_data->get();
		$get_topup['order_statuses'] = Constant::getOrderList( true );
		return View::make( 'export.topup' )->with( $get_topup );
	}
	
	/**
	 * 
	 * 
	 */
	private function _cancelClientOrder( $multiple_order_id ){
		$cancel_order=Order::select( 'company.code','order.EMPLOYEE_id','order.id','order.status' )
		->join( 'company','order.COMPANY_id','=','company.id' )
		->where( 'order.id', '=', array( $multiple_order_id ) )
		->get();

		/*Webservice::getRequestApi( 'update_topup_client', array($cancel_order->code, $cancel_order->EMPLOYEE_id,
		$cancel_order->id, $cancel_order->status ) );*/
	}
}